package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.Result;
import com.itheima.domain.Permission;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.*;

/**
 * @author Zhang_Han
 * @version 1.0
 * @date 2020/10/11 18:34
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Reference
    private UserService userService;

    @RequestMapping("/getUserInfo")
    public Result getUserInfo(Principal principal) {
        try {
            String name = principal.getName();
            User user = userService.findByUsername(name);
            List<String> roleAndPerList = new ArrayList<>();
            Set<Role> roles = user.getRoles();
            if (roles != null && roles.size() > 0) {
                for (Role role : roles) {
                    roleAndPerList.add(role.getKeyword());
                    Set<Permission> permissions = role.getPermissions();
                    if (permissions != null && permissions.size() > 0) {
                        for (Permission permission : permissions) {
                            roleAndPerList.add(permission.getKeyword());
                        }
                    }
                }
            }
            Map map = new HashMap();
            map.put("username", name);
            map.put("roleAndPerList", roleAndPerList);
            return new Result(true, "查询成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询失败");
        }
    }

}
